%% This code creates Table 8.

clear;

final = cell(7,5);

for i = 1:5

    load(['CM_J_Model_',num2str(i),'.mat'], 'Lambda_hat_AJX', 'Vn_AJX','R2_t');

    for k = 1:(i)
   
        arr{i,k}   = [k, (i) + k];

        % Ensure formatting for the chi2cdf calculations

        R = [1,-1];
        chi2_value_full = 1 - chi2cdf((R*Lambda_hat_AJX(:,arr{i,k})')'*inv(R*Vn_AJX(arr{i,k},arr{i,k})*R')*(R*Lambda_hat_AJX(:,arr{i,k})'), 1);

        % Check if the p-values are less than 0.001, otherwise format with 3 decimal places
      
            if chi2_value_full < 0.001
                final(k,i) = {'<0.001'};
            else
                final(k,i) = {sprintf('%.3f', chi2_value_full)};
            end


       
    end

    arr_C{i} = [1:(i)]; 
    chi2_value_C = 1 - chi2cdf(Lambda_hat_AJX(:,arr_C{i})*inv(Vn_AJX(arr_C{i},arr_C{i}))*Lambda_hat_AJX(:,arr_C{i})', (i));
    if chi2_value_C < 0.001
                
        final(6,i) = {'<0.001'};
    
    else
    
        final(6,i) = {sprintf('%.3f', chi2_value_C)};
    
    end


    arr_AJ{i} = [((i)+1):2*(i)]; 
    chi2_value_AJ = 1 - chi2cdf(Lambda_hat_AJX(:,arr_AJ{i})*inv(Vn_AJX(arr_AJ{i},arr_AJ{i}))*Lambda_hat_AJX(:,arr_AJ{i})', (i));
    if chi2_value_AJ < 0.001
                
        final(7,i) = {'<0.001'};
    
    else
    
        final(7,i) = {sprintf('%.3f', chi2_value_AJ)};
    
    end


end

T = cell2table(final);
writetable(T, 'CM_Tests_Results.csv')
  
%  